package cn.yqn.service.impl;

import cn.yqn.contsants.CourseConstants;
import cn.yqn.domain.CourseType;
import cn.yqn.mapper.CourseTypeMapper;
import cn.yqn.service.ICourseTypeService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程目录 服务实现类
 * </p>
 *
 * @author director
 * @since 2022-09-02
 */
@Service
public class CourseTypeServiceImpl extends ServiceImpl<CourseTypeMapper, CourseType> implements ICourseTypeService {

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Autowired
    private CourseTypeMapper courseTypeMapper;

    @Override // redis的key值：courseType::tree ,并且该方法的返回值就是value
    @Cacheable(cacheNames = CourseConstants.COURSE_TYPE_TREE, key = "'tree'")
    public List<CourseType> treeData() {
        return tree();
    }

    /**
    * @Title: 查询树数据
    * @Description: TODO
    * @Author: YQN
    * @Version: 1.0
    * @Date:  2022/9/2 19:54
    * @Parameters: []
    * @Return java.util.List<cn.yqn.domain.CourseType>
    */
    private List<CourseType> tree() {
        List<CourseType> courseTypes = selectList(null);
        Map<Long, CourseType> collectMap = courseTypes.stream().collect(Collectors.toMap(CourseType::getId, item -> item));
        List<CourseType> treeData = new ArrayList<>();
        courseTypes.forEach(e->{
            if (e.getPid() == null || e.getPid().intValue() == 0) {
                treeData.add(e);
            } else {
              collectMap.get(e.getPid()).getChildren().add(e);
            }
        });
        return treeData;
    }
    @Override
    //@Transactional // 当我们一个方法有多次数据更改操作时，这时候我们需要加事务
    @CacheEvict(cacheNames = CourseConstants.COURSE_TYPE_TREE, key = "'tree'")
    public boolean insert(CourseType entity) {
        return super.insert(entity);
    }


    @Override
    @CacheEvict(cacheNames = CourseConstants.COURSE_TYPE_TREE, key = "'tree'")
    public boolean updateById(CourseType entity) {
        return super.updateById(entity);
    }


    @Override
    @CacheEvict(cacheNames = CourseConstants.COURSE_TYPE_TREE, key = "'tree'")
    public boolean deleteById(Serializable id) {
        return super.deleteById(id);
    }

}
